<template>
  <div class="play" v-show="playingList.length>0">
    <div class="normal-play" v-show="fullScreen">
      <div class="top topHead">
        <img src="./backed.png" alt="" @click="back()" class="back">
        <div class="title">
          <div class="TextScroll" ref="textScrollWidth">
            <p v-show="show">{{currentSong.name}}</p>
            <text-scroll :dataList="dataList" :show="show" ref="textScroll"></text-scroll>
          </div>
          <div class="copywriter">
            <span v-for="item, index in currentSong.ar"><span v-show="index>0">/</span>{{item.name}}</span>
          </div>
        </div>
        <img src="./share.png" alt="分享" class="share">
      </div>
      <transition name="bgFade">
        <div class="bgImg" v-if="currentSong.al" :style="`background-image: url(//music.163.com/api/img/blur/${currentSong.al.pic_str})`"
             v-show="imgShow"></div>
      </transition>
      <div class="middleLyric"  v-show="lyricShow" ref="middleLyric" @click="showLyric()">
        <div v-show="!currentLyric" class="lyricReady">
          <p>加载歌词中...</p>
        </div>
        <scroll ref="lyricList" :data="currentLyric && currentLyric.lines" class="lyric">
          <div class="lyric-wrapper" ref="wrapper">
            <div v-if="currentLyric" @click.stop="showLyric()">
              <p ref="lyricLine"
                 class="text"
                 :class="{'current': currentLineNum ===index}"
                 v-for="(line,index) in currentLyric.lines">{{line.txt}}</p>
            </div>
          </div>
        </scroll>
      </div>
      <div class="middle" @click="showLyric()" v-show="!lyricShow">
        <div class="needle">
          <span></span>
          <img src="./stick_bg.png" alt="" ref="needle" :class="{'active':playing&&isReady}">
        </div>
        <div class="cd">
          <div class="playImg" ref="playImg" v-if="currentSong.al&&!lyricShow" :class="cdRotate">
            <img :src="currentSong.al.picUrl" alt="" width="130px" height="130px">
            <span class="coverImg"></span>
          </div>
        </div>
      </div>
      <div class="footer">
        <div class="more" v-show="!lyricShow">
          <img src="./collection.png" alt="">
          <img src="./down.png" alt="">
          <img src="./message.png" alt="">
          <img src="./more.png" alt="">
        </div>
        <div class="schedule">
          <span class="time">{{secToTime(currentTime)}}</span>
          <progress-bar :percent="percent" :fullScreen="fullScreen" ref="progressBar"
                        :buffered="buffered1" @percentChange="percentChange"></progress-bar>
          <span class="time fr">{{secToTime(currentSong.dt / 1000)}}</span>
        </div>
        <div class="mode">
          <img :src="icoMode" alt="" @click="changeMode()">
          <img src="./pre.png" alt="" @click="prev()">
          <img :src="playIcon" alt="" @click="togglePlaying()">
          <img src="./next.png" alt="" @click="next()">
          <img src="./list1.png" alt="" @click="playListShow()">
        </div>
      </div>
      <transition name="prompt">
        <span class="modePrompt" v-show="showModeMsg">{{modeMsg}}</span>
      </transition>
    </div>
    <div class="mimi-play" v-show="!fullScreen">
      <img :src="currentSong.al.picUrl" alt="" class="picUrl" v-if="currentSong.al" @click="open()">
      <div class="song" @click="open()">
        <span>{{currentSong.name}}</span>
        <span v-show="!playing || !playingLyric"><span v-for="singer, index in currentSong.ar"><span v-if="index>0">/</span>{{singer.name}}</span></span>
        <div v-show="playingLyric&&playing">
          <p>{{playingLyric}}</p>
        </div>
      </div>
      <img src="./list.png" alt="" class="fr list icon" @click="playListShow()">
      <progress-circle :percent="percent" :playing="playing" :fullScreen="fullScreen" @togglePlaying="togglePlaying"
                       ref="progressCircle"></progress-circle>
    </div>
    <playList ref="playList"></playList>
    <audio ref="audio" :src="musicUrl" @canplay="ready" @timeupdate="timeUpdate" @progress="progress"
           @ended="end"></audio>
    <p class="setWidth" ref="setWidth">{{currentSong.name}}</p>
    <p class="setNeedle" ref="setNeedle"></p>
  </div>
</template>

<script type="text/ecmascript-6">
  import {mapGetters, mapMutations} from 'vuex'
  import {playMode} from '../../common/js/config'
  import TextScroll from '../../base/text-scroll/text-scroll.vue'
  import ProgressBar from '../../base/progress-bar/progress-bar.vue'
  import ProgressCircle from '../../base/progress-circle/progress-circle.vue'
  import Lyric from 'lyric-parser'
  import Scroll from '../../base/scroll/scroll.vue'
  import PlayList from '../playList/playList.vue'
  import {playModeMixin} from '../../common/js/mixin/playMode'
  const ERROk = 200
  export default {
    mixins: [playModeMixin],
    data() {
      return {
        musicUrl: String,
        isReady: false,
        show: true,
        imgShow: false,
        dataList: [],
        currentTime: 0,
        playingLyric: '',
        currentLyric: null,
        currentLineNum: 0,
        lyricShow: false,
        listShow: false
      }
    },
    created() {
      this.click = false
    },
    methods: {
      playListShow() {
        this.$refs.playList.show()
      },
      getMusicUrl(id) {
        this.$ajax.get(`/music/url?id=${id}`).then((response) => {
          if (response.data.code === ERROk) {
            this.musicUrl = response.data.data[0].url
            this.imgShow = true
          }
        })
      },
      getLyric(id) {
        this.$ajax.get(`/lyric?id=${id}`).then((response) => {
          if (response.data.code === ERROk) {
            this.lyric = response.data.lrc.lyric
            this.currentLyric = new Lyric(this.lyric, this.handleLyric)
            if (this.playing) {
              this.currentLyric.play()
            }
          }
        })
      },
      handleLyric({lineNum, txt}) {
        this.currentLineNum = lineNum
        //  若当前行大于5,开始滚动,以保歌词显示于中间位置
        if (this.lyricShow) {
          if (lineNum > 5) {
            let lineEl = this.$refs.lyricLine[lineNum - 5]
            this.$refs.lyricList.scrollToElement(lineEl, 1000)
          } else {
            this.$refs.lyricList.scrollTo(0, 0, 1000)
          }
        }
        this.playingLyric = txt
      },
      back() {
        this.setFullScreen(false)
      },
      open() {
        this.lyricShow = false
        this.setFullScreen(true)
      },
      ready() {
        this.isReady = true
        if (this.playing) {
          this.$refs.audio.play()
        }
      },
      error() {
        this.isReady = true
      },
      end() {
        if (this.mode === playMode.loop) {
          this.loop()
        } else {
          this.next()
        }
      },
      loop() {
        this.$refs.audio.currentTime = 0
        this.$refs.audio.play()
        this.setPlaying(true)
        if (this.currentLyric) {
          this.currentLyric.seek(0)
        }
      },
      next() {
        if (this.playingList.length === 1) {
          this.loop()
          return
        } else {
          let index = this.currentIndex + 1
          if (index === this.playingList.length) {
            index = 0
          }
          this.setCurrentIndex(index)
          if (!this.playing) {
            this.setPlaying(!this.playing)
          }
        }
        this.isReady = false
      },
      prev() {
        if (this.playingList.length === 1) {
          this.loop()
          return
        } else {
          let index = this.currentIndex - 1
          if (index === -1) {
            index = this.playingList.length - 1
          }
          this.setCurrentIndex(index)
          if (!this.playing) {
            this.setPlaying(!this.playing)
          }
        }
        this.isReady = false
      },
      progress() {
        if (this.isReady) {
          // 缓冲进度
          this.buffered = this.$refs.audio.buffered.end(0)
        } else {
          this.buffered = 0
        }
      },
      timeUpdate() {
        this.currentTime = this.$refs.audio.currentTime
      },
      togglePlaying() {
        if (!this.isReady) {
          return
        }
        this.setPlaying(!this.playing)
        this.currentLyric.togglePlay()
      },
      percentChange(percent) {
        this.currentTime = this.currentSong.dt / 1000 * percent
        this.$refs.audio.currentTime = this.currentTime
        if (this.currentLyric && this.playing) {
          this.currentLyric.seek(this.currentTime * 1000)
        }
      },
      showLyric() {
        this.lyricShow = !this.lyricShow
        if (this.lyricShow) {
          this.$nextTick(() => {
            this.$refs.lyricList.refresh()
          })
        }
      },
      secToTime(t) {
        t = t | 0
        let minute = t / 60 | 0
        let second = (t % 60)
        if (minute < 10) {
          minute = '0' + minute
        }
        if (second < 10) {
          second = '0' + second
        }
        return `${minute}:${second}`
      },
      ...mapMutations({
        setFullScreen: 'SET_FULL_SCREEN'
      })
    },
    computed: {
      playIcon() {
        return this.playing ? require('./pause.png') : require('./play.png')
      },
      cdRotate() {
        return this.playing ? 'play' : 'pause play'
      },
      percent() {
        return this.currentTime / (this.currentSong.dt / 1000)
      },
      buffered1() {
        return this.buffered / (this.currentSong.dt / 1000)
      },
      ...mapGetters([
        'fullScreen',
        'playing',
        'currentIndex'
      ])
    },
    watch: {
      playing(newPlaying) {
        if (this.isReady) {
          newPlaying ? this.$refs.audio.play() : this.$refs.audio.pause()
        }
        if (newPlaying && this.currentLyric) {
          this.currentLyric.seek(this.currentTime * 1000)
        }
      },
      fullScreen() {
        if (this.fullScreen) {
          this.$nextTick(() => {
            const progressWidth = this.$refs.progressBar.$refs.progress.clientWidth
            const circleWidth = this.$refs.progressBar.$refs.circle.clientWidth
            const offsetWidth = this.percent * (progressWidth - circleWidth)
            this.$refs.progressBar.setWidth(offsetWidth)
          })
        } else {
          this.$nextTick(() => {
            this.$refs.progressCircle.getPerimeter()
            this.$refs.progressCircle.setDashArray(this.percent)
          })
        }
      },
      currentSong(newSong, oldSong) {
        console.log(newSong, oldSong)
        if (!newSong.id) {
          return
        }
        if (newSong.id === oldSong.id) {
          return
        }

        if (this.currentLyric) {
          this.imgShow = false
          this.currentLyric.stop()
          this.currentTime = 0
          this.playingLyric = ''
          this.currentLineNum = 0
          this.currentLyric = null
        }
        this.getMusicUrl(newSong.id)
        this.getLyric(newSong.id)
        this.currentTime = 0
        this.isReady = false
      }
    },
    components: {
      TextScroll,
      Scroll,
      ProgressBar,
      ProgressCircle,
      PlayList
    }
  }
</script>

<style>
  .play .top {
    border-bottom: 1px solid rgba(222, 222, 222, .3);
  }

  .mimi-play {
    position: fixed;
    bottom: 0;
    z-index: 1000;
    width: 100%;
    height: 4.5rem;
    background: #f3eeee;
  }

  .mimi-play .song {
    display: inline-block;
    width: calc(100% - 12rem);
    height: 4.5rem;
    padding-top: 0.5rem;
    font-size: 1rem;
  }

  .mimi-play .song > span {
    display: inline-block;
    width: 100%;
    overflow: hidden;
    white-space: nowrap;
  }

  .mimi-play .song p {
    width: 100%;
    overflow: hidden;
    white-space: nowrap;
  }

  .mimi-play .icon {
    position: relative;
    margin: 1rem 1rem 0 0;
    width: 2.5rem;
    height: 2.5rem;
  }

  .mimi-play svg {
    position: relative;
    margin: 0.25rem 0 0 0.25rem;
  }

  .mimi-play .icon span {
    position: absolute;
    top: 0.85rem;
    display: inline-block;
    width: 0.1rem;
    height: 0.8rem;
    background-color: #f00;
  }

  .mimi-play .icon span.left {
    left: 1rem;
  }

  .mimi-play .icon span.right {
    right: 1rem;
  }

  .mimi-play circle {
    position: absolute;
  }

  .mimi-play .icon .round {
    width: 2rem;
    height: 2rem;
    margin: 0.25rem auto;
    border: 0.2rem solid #000;
    border-radius: 50%;
    text-align: center;
  }

  .mimi-play .icon .round.play {
    border-color: #000;
  }

  .icon .round .tri {
    display: inline-block;
    width: 0px;
    height: 0px;
    border-top: 0.5rem solid transparent;
    border-left: 1rem solid black;
    border-bottom: 0.5rem solid transparent;
    margin-left: 0.25rem;
  }

  .mimi-play .icon .round.pause {
    border-color: #ccc;
  }

  .mimi-play .round.pause span {
    width: 0.1rem;
    display: inline-block;
    height: 1rem;
    background: #f00;
  }

  .mimi-play .picUrl {
    width: 3.5rem;
    height: 3.5rem;
    margin: 0.5rem;
    vertical-align: top;
  }

  .mimi-play img.list {
    margin-right: 1rem;
  }

  .normal-play {
    position: fixed;
    top: 0;
    bottom: 0;
    left: 0;
    right: 0;
    z-index: 1000;
    background: #222;
  }

  .normal-play .bgImg {
    z-index: -1;
  }

  .normal-play .playImg img {
    position: absolute;
    top: 34px;
    left: 34px;
    border-radius: 50%;
  }

  .normal-play .top {
    height: 4rem;
  }

  .normal-play .top .title {
    width: calc(100% - 8rem);
  }

  .normal-play .top img {
    position: absolute;
    top: 1rem;
    width: 2rem;
    height: 2rem;
  }

  .normal-play .schedule {
    color: #fff;
    font-size: 1rem;
    margin: 1.5rem 0;
  }

  .normal-play .schedule .progress {
    width: calc(100% - 10rem);
    height: 0.2rem;
    background: #8e8b8b;
    vertical-align: middle;
    display: inline-block;
    position: relative;
  }

  .normal-play .progress .line, .normal-play .progress .buffered {
    position: absolute;
    height: 0.2rem;
    width: 0;
    background: #f00;
  }

  .normal-play .progress .buffered {
    background: #ccc;
  }

  .normal-play .progress .circle {
    position: absolute;
    top: -0.5rem;
    left: 0;
    width: 1rem;
    height: 1rem;
    background: #fff;
    border-radius: 50%;
  }

  .normal-play .schedule span {
    display: inline-block;
  }

  .normal-play .schedule .time {
    width: 4.7rem;
    padding-left: 0.3rem;
  }

  .normal-play .schedule .time:first-child {
    text-align: right;
    padding: 0 0.3rem 0 0;
  }

  .normal-play .footer {
    width: 100%;
    position: absolute;
    bottom: 2rem;
  }

  .normal-play .top img.back {
    left: 1rem;
  }

  .normal-play .top img.share {
    right: 1rem;
  }

  .normal-play .more, .normal-play .mode {
    text-align: center;
  }

  .normal-play .more img, .normal-play .mode img {
    width: 2rem;
    margin: 0 1.5rem;
  }

  .normal-play .middleLyric {
    height: calc(100% - 15.5rem);
    width: 100%;
  }

  .normal-play .lyric {
    height: 100%;
    text-align: center;
    overflow: hidden;
  }

  .middle {
    height: calc(100% - 15.5rem);
  }

  .normal-play .lyric .text {
    line-height: 3rem;
    color: #9e9c9c;
    font-size: 1.5rem;
  }

  .normal-play .lyric .text.current {
    color: #fff;
  }

  .cd {
    position: relative;
    top: -3rem;
  }

  .playImg {
    position: relative;
    width: 198px;
    height: 198px;
    margin: 0 auto;
  }

  .playImg.play {
    animation: rotate 40s linear infinite
  }

  .playImg.pause {
    animation-play-state: paused
  }

  .coverImg {
    position: absolute;
    top: -4px;
    left: -4px;
    display: inline-block;
    width: 206px;
    height: 205px;
    background: url('./coverall.png') no-repeat -140px -580px;
  }

  .needle {
    position: relative;
    z-index: 10;
    text-align: center;
    overflow: hidden;
  }

  .needle img {
    width: 6rem;
    margin-top: -13px;
    transform: rotate(-30deg);
    transform-origin: 13px 13px;
    transition: all .5s linear;
  }

  .needle img.active {
    transform: rotate(-3deg);
  }

  .lyricReady {
    position: absolute;
    top: 49%;
    width: 100%;
    text-align: center;
    font-size: 1.5rem;
    color: #9e9c9c;
  }
  .showLyric{
    position: absolute;
    top: 0;
    bottom: 0;
    left: 0;
    right: 0;
    z-index: 100;
  }
  .setNeedle {
    width: 1rem;
    visibility: hidden;
  }

  @keyframes rotate {
    0% {
      transform: rotate(0deg)
    }
    100% {
      transform: rotate(360deg)
    }
  }
  .modePrompt{
    display: inline-block;
    position: absolute;
    bottom: 5rem;
    left: 50%;
    transform: translateX(-50%);
    padding: .7rem 1.5rem;
    border-radius: 2rem;
    color: #fff;
    background: #969595;
    font-size: 1rem;
  }
  .bgFade-enter-active, .bgFade-leave-active, .prompt-enter-active, .prompt-leave-active {
    transition: .5s all linear;
  }

  .bgFade-enter, .bgFade-leave-to, .prompt-enter, .prompt-leave-to{
    opacity: 1;
  }
</style>
